package cn.kgc.watch.service.impl;

import cn.kgc.watch.entity.Cart;
import cn.kgc.watch.entity.CartShopping;
import cn.kgc.watch.entity.Order;
import cn.kgc.watch.entity.OrderDetail;
import cn.kgc.watch.mapper.*;
import com.github.pagehelper.util.StringUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import cn.kgc.watch.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService{

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private CommoditySkuMapper commoditySkuMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private CartMapper cartMapper;
    @Resource
    private CartShoppingMapper cartShoppingMapper;
    @Override
    public List<Order> findOrderByUserId(Integer userId) {
        return this.orderMapper.selectOrderByUserId(userId);
    }
    @Transactional
    @Override
    public Long orderGo(Order order) {
        order.setCreateTime(new Date());
        String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
        order.setOrderNumber(uuid);
        this.orderMapper.insertOrder(order);
        for (OrderDetail orderDetail : order.getOrderDetailList()) {
            orderDetail.setOrder(new Order(order.getOrderId()));
            orderDetail.setUserId(order.getUser().getUserId());
            this.orderDetailMapper.insertOrderDetail(orderDetail);
            this.commoditySkuMapper.updateStock(orderDetail.getCommoditySku().getId(),orderDetail.getCommoditySum());
        }
        Cart cart = this.cartMapper.selectCartByUserId(order.getUser().getUserId());
        for (CartShopping cartShopping : cart.getCartShoppingList()) {
            for (OrderDetail orderDetail : order.getOrderDetailList()) {
                if(orderDetail.getCommoditySku().getId()==cartShopping.getCommoditySku().getId()){
                    this.cartShoppingMapper.deleteCartShoppingByOrder(cart.getId(),orderDetail.getCommoditySku().getId());
                }
            }
        }
        this.userMapper.updateTotalAmount(order.getUser().getUserId(),order.getTotalAmount());
        return order.getOrderId();
    }
    @Override
    public List<Order> findUserOrder(Integer id) {
        return this.orderMapper.selectUserOrder(id);
    }

    @Override
    public void modifyOrderState(Order order) {
        this.orderMapper.updateOrderState(order);
    }

    @Override
    public void modifyOrderPay(Order order) {
        this.orderMapper.updateOrderPay(order);
    }
}
